﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.CommonServiceLocator;
using CommonServiceLocator;
using Digitalmes.Configuration;
using Digitalmes.Services;
using Digitalmes.Services.Hosted;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MQTTnet.AspNetCore;
using NetBox.Extensions;
using Serilog;
using System;
using System.Collections.Generic;
using WalkingTec.Mvvm.Core;


namespace Digitalmes
{
    public class Program
    {

        public static ILifetimeScope Container { get; private set; }    
        public static async Task Main(string[] args)
        {
            // 创建根容器并注册全局依赖项
            var containerBuilder = new ContainerBuilder();


            Container = containerBuilder.Build();


         


            string LogFilePath = $@"{AppContext.BaseDirectory}Logs/log-.log";
            // 配置 Serilog
            Log.Logger = new LoggerConfiguration()            
                .WriteTo.File(
                     path: LogFilePath,         // 日志路径
                    rollingInterval: RollingInterval.Day, // 按天分割
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
                )
                .CreateLogger();

            try
            {
               var host= CreateWebHostBuilder(args).Build();

                // 在主机构建完成后设置ServiceLocator
                Container= host.Services.GetAutofacRoot();
                var csl = new AutofacServiceLocator(Container);
                ServiceLocator.SetLocatorProvider(() => csl);

                //host.Run();

                await Task.WhenAll(host.RunAsync());
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }


            //CreateWebHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateWebHostBuilder(string[] args)
        {

            var maincon = new AutofacChildLifetimeScopeServiceProviderFactory(Container.BeginLifetimeScope("Main"));
            //var maincon = new AutofacServiceProviderFactory();

            var csl = new AutofacServiceLocator(Container);

            ServiceLocator.SetLocatorProvider(() => csl);

            return
                Host.CreateDefaultBuilder(args)
                .UseWindowsService()
                .UseServiceProviderFactory(maincon)
                .UseContentRoot(AppContext.BaseDirectory)
                .ConfigureServices((services) =>
                 {
                     // 注册 Serilog 适配器作为日志服务
                     services.AddTransient<ILogService>(provider =>
                         new SerilogAdapter(Log.Logger));

                     services.AddHostedService<AppBackgroupService>();
                     services.AddHostedService<AppHostedService>();
                    
                 })
                  .ConfigureAppConfiguration((hostingContext, config) =>
                  {
                      config.AddInMemoryCollection(new Dictionary<string, string> { { "HostRoot", hostingContext.HostingEnvironment.ContentRootPath } });
                  })
                 .ConfigureLogging((hostingContext, logging) =>
                 {
                     logging.ClearProviders();
                     logging.AddConsole();                  
                     logging.AddWTMLogger();
                 })
                .ConfigureWebHostDefaults(webBuilder =>
                 {
                     string[] urls = [];
                     webBuilder.UseKestrel((context, o) =>
                     {


                         var mqttset = context.Configuration.GetSection("MqttSettings").Get<MqttSettings>();


                          // This will allow MQTT connections based on TCP port 1883.
                          o.ListenAnyIP(mqttset.TcpEndpoint.Port, l => l.UseMqtt());


                          // 从配置中获取Domains:server:Address
                          var serverAddress = context.Configuration["Domains:server:Address"];
                          var uri = new Uri(serverAddress);
                          var port = uri.Port;
                         // urls.Append(serverAddress);
                         // This will allow MQTT connections based on HTTP WebSockets with URI "localhost:5000/mqtt"
                         // See code below for URI configuration.
                         o.ListenAnyIP(uri.Port, listenOptions =>
                         {
                             listenOptions.Protocols = HttpProtocols.Http1AndHttp2; // 明确指定HTTP协议
                         });
                     });

                  
                     webBuilder.UseStartup<Startup>();
                    // webBuilder.UseUrls(urls);
                     webBuilder.UseWebRoot("wwwroot").UseStaticWebAssets();
                 });
        }
    }
}
